package com.woniu108.product.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.dto.AdminInfoDto;
import com.woniu108.carService.commos.dto.ProductItemDto;
import com.woniu108.carService.commos.dto.UserInfoDto;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.produnt.ProductException;
import com.woniu108.carService.commos.exception.produnt.ProductExceptionCode;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.product.client.EvaluateClient;
import com.woniu108.product.client.PersonClient;
import com.woniu108.product.mapper.ProductBrandMapper;
import com.woniu108.product.mapper.ProductInfoMapper;
import com.woniu108.product.mapper.ProductItemMapper;
import com.woniu108.product.mapper.ProductTypeMapper;
import com.woniu108.product.model.ProductBrand;
import com.woniu108.product.model.ProductInfo;
import com.woniu108.product.model.ProductItem;
import com.woniu108.product.model.ProductType;
import com.woniu108.product.param.*;
import com.woniu108.product.service.ProductItemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商品总览 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class ProductItemServiceImpl extends ServiceImpl<ProductItemMapper, ProductItem> implements ProductItemService {
    @Resource
    private ProductItemMapper productItemMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private ProductBrandMapper productBrandMapper;
    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private PersonClient personClient;
    @Resource
    private EvaluateClient evaluateClient;

    /**
     * 判断管理员
     */
    private void isAdmin(String adminId) {
        // 检查 adminId 是否为 null
        if (adminId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断管理员权限
        AdminInfoDto adminInfo = personClient.getByAdminId(adminId).getData();
        if (adminInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
        if (adminInfo.getAdminRoleId() != 1&&adminInfo.getAdminRoleId() != 2) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_PERMISSION);
        }
    }


    /**
     * 判断用户
     */
    private void isUser(String userId) {
        // 检查 userId 是否为 null
        if (userId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断用户
        UserInfoDto userInfo = personClient.getByUserId(userId).getData();
        if (userInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
    }

    /**
     * 将items转为dto对象
     */
    private List<ProductItemDto> itemsToDtos(List<ProductItem> items) {
        ArrayList<ProductItemDto> dtos = new ArrayList<>();
        for (ProductItem item : items) {
            ProductItemDto dto = BeanUtil.toBean(item, ProductItemDto.class);
            //查种类名
            ProductType type = productTypeMapper.selectById(dto.getPTId());
            dto.setPTName(type.getPTName());
            //查品牌名
            ProductBrand brand = productBrandMapper.selectById(dto.getPBId());
            dto.setPBName(brand.getPBName());
            //加入集合
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public List<ProductItemDto> findAllProductItem(FindAllProductItemParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        QueryWrapper<ProductItem> wrapper = new QueryWrapper<>();
        wrapper.ne("pro_state", StaticData.PRODUCT_ITEM_STATE_DELETE);
        //判断品牌id
        if (param.getPBId() != null) {
            wrapper.eq("p_b_id", param.getPBId());
        }
        //判断种类id
        if (param.getPTId() != null) {
            wrapper.eq("p_t_id", param.getPTId());
        }
        List<ProductItem> items = productItemMapper.selectList(wrapper);
        //将items转为dto对象
        return itemsToDtos(items);
    }

    @Override
    public List<ProductItemDto> findAllNormalProductItem(FindAllNormalProductItemParam param) {
        //判断用户
        isUser(param.getUserId());
        QueryWrapper<ProductItem> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_state", StaticData.PRODUCT_ITEM_STATE_NORMAL);
        //判断品牌id
        if (param.getPBId() != null) {
            wrapper.eq("p_b_id", param.getPBId());
        }
        //判断种类id
        if (param.getPTId() != null) {
            wrapper.eq("p_t_id", param.getPTId());
        }
        List<ProductItem> items = productItemMapper.selectList(wrapper);
        //将items转为dto对象
        return itemsToDtos(items);
    }

    @Override
    public Boolean insertProductItem(InsertProductItemParam param) {
        //判断是否为管理员
        isAdmin(param.getAdminId());
        //查询该商品名是否存在
        QueryWrapper<ProductItem> wrapper = new QueryWrapper<>();
        wrapper.eq("p_name", param.getPName());
        ProductItem selectOne = productItemMapper.selectOne(wrapper);
        //判断存不存在
        if (selectOne != null) {
            //存在状态正常或禁用就报错
            if (Objects.equals(selectOne.getProState(), StaticData.PRODUCT_ITEM_STATE_BAN) || Objects.equals(selectOne.getProState(), StaticData.PRODUCT_ITEM_STATE_NORMAL)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_HAVE);
            }
            //删除状态就改为正常
            selectOne.setProState(StaticData.PRODUCT_ITEM_STATE_NORMAL);
            selectOne.setCreateTime(LocalDateTime.now());
            int update = productItemMapper.updateById(selectOne);
            return update > 0;
        }
        //不存在就新增
        ProductItem item = new ProductItem();
        item.setPName(param.getPName());
        item.setPBId(param.getPBId());
        item.setPTId(param.getPTId());
        item.setPayNum(0);
        item.setProState(StaticData.PRODUCT_ITEM_STATE_NORMAL);
        item.setCreateTime(LocalDateTime.now());
        int insert = productItemMapper.insert(item);
        evaluateClient.createProductScoreByPItemId(item.getPItemId());
        return insert > 0;
    }

    @Override
    public Boolean updateProductItem(UpdateProductItemParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        //通过id查商品
        ProductItem select = productItemMapper.selectById(param.getPItemId());
        if (select == null || Objects.equals(select.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
        }
        //通过名字查，看新名字是否同名
        QueryWrapper<ProductItem> wrapper = new QueryWrapper<>();
        wrapper.eq("p_name", param.getPName());
        ProductItem selectOne = productItemMapper.selectOne(wrapper);
        if (selectOne != null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_HAVE);
        }
        //修改名字
        select.setPName(param.getPName());
        int i = productItemMapper.updateById(select);
        return i > 0;
    }

    @Override
    public Boolean banProductItem(BanProductItemParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        for (Integer pItemId : param.getPItemIds()) {
            //禁用商品总览
            ProductItem productItem = productItemMapper.selectById(pItemId);
            //判断是否存在和状态
            if (productItem == null || Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
            }
            if (Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_BAN)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_BANED);
            }
            //禁用
            productItem.setProState(StaticData.PRODUCT_ITEM_STATE_BAN);
            productItemMapper.updateById(productItem);
            //查询是否存在商品详情
            QueryWrapper<ProductInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("p_item_id", productItem.getPItemId()).eq("p_info_state", StaticData.PRODUCT_INFO_STATE_NORMAL);
            List<ProductInfo> infos = productInfoMapper.selectList(infoQueryWrapper);
            // 判断 infos 是否为空
            if (infos.isEmpty()) {
                continue; // 如果没有商品详情，继续处理下一个商品总览
            }
            //禁用商品详情
            for (ProductInfo info : infos) {
                //判断info状态
                if (Objects.equals(info.getPInfoState(), StaticData.PRODUCT_INFO_STATE_NORMAL)) {
                    //禁用
                    info.setPInfoState(StaticData.PRODUCT_INFO_STATE_BAN);
                    productInfoMapper.updateById(info);
                }
            }
        }
        return true;
    }

    @Override
    public Boolean unlockProductItem(UnlockProductItemParam param) {

        //判断管理员
        isAdmin(param.getAdminId());
        for (Integer pItemId : param.getPItemIds()) {
            //解锁商品总览
            ProductItem productItem = productItemMapper.selectById(pItemId);
            //判断是否存在和状态
            if (productItem == null || Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
            }
            if (Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_NORMAL)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_STATE_NORMAL);
            }
            //判断种类状态
            ProductType type = productTypeMapper.selectById(productItem.getPTId());
            if (Objects.equals(type.getPTState(), StaticData.PRODUCT_TYPE_STATE_BAN) || Objects.equals(type.getPTState(), StaticData.PRODUCT_TYPE_STATE_DELETE)) {
                throw new ProductException(500, "有种类被禁用中，无法解禁");
                // 如果种类状态是被禁用或删除，继续处理下一个商品总览
            }
            //判断品牌状态
            ProductBrand brand = productBrandMapper.selectById(productItem.getPBId());
            if (Objects.equals(brand.getPBState(), StaticData.PRODUCT_BRAND_STATE_BAN) || Objects.equals(brand.getPBState(), StaticData.PRODUCT_BRAND_STATE_DELETE)) {
                throw new ProductException(500, "有品牌被禁用中，无法解禁");
                // 如果品牌状态是被禁用或删除，继续处理下一个商品总览
            }
            //解锁
            productItem.setProState(StaticData.PRODUCT_ITEM_STATE_NORMAL);
            productItemMapper.updateById(productItem);
            //查询是否存在商品详情
            QueryWrapper<ProductInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("p_item_id", productItem.getPItemId()).eq("p_info_state", StaticData.PRODUCT_INFO_STATE_NORMAL);
            List<ProductInfo> infos = productInfoMapper.selectList(infoQueryWrapper);
            // 判断 infos 是否为空
            if (infos.isEmpty()) {
                continue; // 如果没有商品详情，继续处理下一个商品总览
            }
            //解锁商品详情
            for (ProductInfo info : infos) {
                //判断info状态
                if (info.getPInfoState().equals(StaticData.PRODUCT_INFO_STATE_BAN)) {
                    //解锁
                    info.setPInfoState(StaticData.PRODUCT_INFO_STATE_NORMAL);
                    productInfoMapper.updateById(info);
                }
            }
        }
        return true;
    }

    @Override
    public Boolean deleteProductItem(DeleteProductItemParam param) {
        //判断管理员
        isAdmin(param.getAdminId());
        // 如果没有商品 ID，直接返回
        if (param.getPItemIds() == null || param.getPItemIds().isEmpty()) {
            return true;
        }
        for (Integer pItemId : param.getPItemIds()) {
            //删除商品总览
            ProductItem productItem = productItemMapper.selectById(pItemId);
            //判断是否存在和状态
            if (productItem == null || Objects.equals(productItem.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
                throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
            }
            //删除
            productItem.setProState(StaticData.PRODUCT_ITEM_STATE_DELETE);
            //清空销量
            productItem.setPayNum(0);
            productItemMapper.updateById(productItem);
            evaluateClient.delProductScore(pItemId);
            //查询是否存在商品详情
            QueryWrapper<ProductInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("p_item_id", productItem.getPItemId()).eq("p_info_state", StaticData.PRODUCT_INFO_STATE_NORMAL);
            List<ProductInfo> infos = productInfoMapper.selectList(infoQueryWrapper);
            // 判断 infos 是否为空
            if (infos.isEmpty()) {
                continue; // 如果没有商品详情，继续处理下一个商品总览
            }
            //删除商品详情
            for (ProductInfo info : infos) {
                //删除
                info.setPInfoState(StaticData.PRODUCT_INFO_STATE_DELETE);
                productInfoMapper.updateById(info);
            }
        }
        return true;
    }

    @Override
    public Boolean addPayNum(Integer pItemId) {
        // 检查 pItemId 是否为 null
        if (pItemId == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_ID_NULL);
        }
        // 根据 pItemId 查询 ProductItem
        ProductItem item = productItemMapper.selectById(pItemId);
        // 检查 item 是否存在以及状态是否为已删除
        if (Objects.equals(item.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
        }
        // 增加 payNum
        item.setPayNum(item.getPayNum() + 1);
        // 更新数据库中的 ProductItem
        int i = productItemMapper.updateById(item);
        // 返回是否更新成功
        return i > 0;
    }

    @Override
    public Boolean reducePayNum(Integer pItemId) {
        // 检查 pItemId 是否为 null
        if (pItemId == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_ID_NULL);
        }

        // 根据 pItemId 查询 ProductItem
        ProductItem item = productItemMapper.selectById(pItemId);

        // 检查 item 是否存在以及状态是否为已删除
        if (item == null || Objects.equals(item.getProState(), StaticData.PRODUCT_ITEM_STATE_DELETE)) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
        }

        // 检查当前销量是否大于零
        if (item.getPayNum() <= 0) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_PAY_NUM_NOT_ENOUGH);
        }

        // 减少 payNum
        item.setPayNum(item.getPayNum() - 1);

        // 更新数据库中的 ProductItem
        int rowsAffected = productItemMapper.updateById(item);

        // 返回是否更新成功
        return rowsAffected > 0;
    }

    @Override
    public ProductItemDto findProductItemByItemId(Integer pItemId) {
        ProductItem item = productItemMapper.selectById(pItemId);
        if (item == null) {
            throw new ProductException(ProductExceptionCode.PRODUCT_ITEM_NOT_HAVE);
        }
        ProductItemDto dto = BeanUtil.toBean(item, ProductItemDto.class);
        //查种类名
        ProductType type = productTypeMapper.selectById(dto.getPTId());
        dto.setPTName(type.getPTName());
        //查品牌名
        ProductBrand brand = productBrandMapper.selectById(dto.getPBId());
        dto.setPBName(brand.getPBName());
        return dto;
    }
}
